<?php
    require('common.php');
        
    $db = new Database();
    $user = getUser($db);
    
    // Error check
    if($user['group'] < 2) {
        redirect('index.php');
        exit();
    }
    checkCsrfGuard();
    if(!isset($_POST['id']))
        throw new Exception('Bad request.');
    
    // Check that the block exists
    $result = $db->query('SELECT id FROM '.
        config('DB_PREFIX').'blocks WHERE id='.intval($_POST['id']));
    if(mysqli_num_rows($result) < 1)
        throw new Exception('No such block.');
    
    // Remove questions
    $result = $db->query('SELECT id FROM '.
        config('DB_PREFIX').'questions WHERE block='.intval($_POST['id']));
    while($row = mysqli_fetch_assoc($result)) {
        if( !array_key_exists( 'q_old_'.$row['id'], $_POST ) ) {
            $db->query('DELETE FROM '.
                config('DB_PREFIX').'questions WHERE id='.$row['id']);
        }
    }
    
    // Update questions and add new questions
    foreach ($_POST as $key => $value) {
        if( !preg_match('/^(?P<name>(q_old_)|(q_new_))(?P<id>\d+)$/', $key, $matches) )
            continue;
        if( $matches['name'] == 'q_old_' ) {
            if( !isset( $_POST['a_old_'.$matches['id']] ) ) 
                throw new Exception('Missing answer.');
            $db->query('UPDATE '.
                config('DB_PREFIX').'questions SET '.
                'question='.$db->escape( $_POST['q_old_'.$matches['id']] ).', '.
                'answer  ='.$db->escape( $_POST['a_old_'.$matches['id']] ).' '.
                'WHERE id='.$matches['id']);
        }
        if( $matches['name'] == 'q_new_' ) {
            if( !isset( $_POST['a_new_'.$matches['id']] ) ) 
                throw new Exception('Missing answer.');
            if( $_POST['q_new_'.$matches['id']] == '' &&
                $_POST['a_new_'.$matches['id']] == '' )
                continue;
            $db->query('INSERT INTO '.
                config('DB_PREFIX').'questions (question, answer, block) '.
                'VALUES ('.
                $db->escape( $_POST['q_new_'.$matches['id']] ).', '.
                $db->escape( $_POST['a_new_'.$matches['id']] ).', '.
                intval( $_POST['id'] ).
                ')');
        }
    }
    
    // Success
    redirect('blocks.php');
?>